<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form 
      :model="queryParams" 
      ref="queryRef" 
      :inline="true" 
      v-show="showSearch" 
      label-width="68px"
    >
      <el-form-item label="工序编码" prop="processCode">
        <el-input
          v-model="queryParams.processCode"
          placeholder="请输入工序编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工序名称" prop="processName">
        <el-input
          v-model="queryParams.processName"
          placeholder="请输入工序名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="enableFlag">
        <el-select
          v-model="queryParams.enableFlag"
          placeholder="请选择是否启用"
          clearable
          style="width: 100%"
        >
          <el-option label="是" value="Y" />
          <el-option label="否" value="N" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['process:process:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['process:process:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['process:process:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['process:process:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table 
      v-loading="loading" 
      :data="processList" 
      @selection-change="handleSelectionChange"
      border
      stripe
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="工序ID" align="center" prop="processId" width="80" /> -->
      <el-table-column label="工序编码" align="center" prop="processCode" />
      <el-table-column label="工序名称" align="center" prop="processName" />
      <el-table-column prop="enableFlag" label="是否启用" align="center">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.enableFlag === 'Y'">是</el-tag>
          <el-tag type="danger" v-else>否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="工序说明" align="center" prop="attention" class-name="attention-column">
        <template #default="scope">
          <!-- 动态判断：是否显示完整内容 -->
          <div 
            class="attention-content"
            :class="{ 'show-full': scope.row.showFullAttention }"
            @click="toggleAttention(scope.row)"
          >
            {{ scope.row.attention || '-' }}
          </div>
          <!-- 点击提示（仅文本超出时显示） -->
          <span 
            class="expand-tip"
            v-if="scope.row.attention && isTextOverflow(scope.row.attention)"
          >
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['process:process:edit']"
          >修改</el-button>
          <el-button 
            link 
            type="primary" 
            icon="Delete" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['process:process:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工序对话框 -->
    <el-dialog 
      :title="title" 
      v-model="open" 
      width="900px" 
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form 
        ref="processRef" 
        :model="form" 
        :rules="rules" 
        size="default" 
        label-width="100px"
      >
        <el-row gutter="15">
          <el-col :span="14">
            <el-form-item label="工序编码" prop="processCode">
              <el-input 
                v-model="form.processCode" 
                type="text" 
                placeholder="请输入工序编码" 
                clearable
                :disabled="form.autoGenerate" 
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="自动生成" prop="autoGenerate">
              <el-switch 
                v-model="form.autoGenerate" 
                @change="handleAutoGenerate"
                active-text="开启"
                inactive-text="关闭"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="15">
          <el-col :span="22">
            <el-form-item label="工序名称" prop="processName">
              <el-input 
                v-model="form.processName" 
                type="text" 
                placeholder="请输入工序名称" 
                clearable
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="15">
          <el-col :span="22">
            <el-form-item label="是否启用" prop="enableFlag">
              <el-radio-group v-model="form.enableFlag" size="default">
                <el-radio label="Y">是</el-radio>
                <el-radio label="N">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="15">
          <el-col :span="22">
            <el-form-item label="工序说明" prop="attention">
              <el-input 
                v-model="form.attention" 
                type="textarea" 
                placeholder="请输入工序说明"
                :autosize="{minRows: 3, maxRows: 5}" 
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="15">
          <el-col :span="22">
            <el-form-item label="备注" prop="remark">
              <el-input 
                v-model="form.remark" 
                type="textarea" 
                placeholder="请输入备注"
                :autosize="{minRows: 3, maxRows: 5}" 
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
          <el-tabs type="border-card">
            <el-tab-pane label=" 操作步骤">
                   <ProcessContent 
                      v-if="form.processId" 
                      :current-processId="form.processId"
                    ></ProcessContent>
            </el-tab-pane>
          </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Process">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { listProcess, getProcess, delProcess, addProcess, updateProcess } from "@/api/process/process";
// 如需后端生成编码，取消下面注释并使用
// import { generateProcessCode } from "@/api/process/process";
import ProcessContent from '@/views/processcontent/processcontent/index.vue'
// 获取当前组件实例
const { proxy } = getCurrentInstance();

// 响应式数据
const processList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 表单数据与查询参数
const data = reactive({
  form: {
    autoGenerate: true,  // 默认开启自动生成编码
    processId: null,
    processCode: "",
    processName: "",
    attention: "",
    enableFlag: "Y",     // 默认启用
    remark: "",
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    processCode: null,
    processName: null,
    enableFlag: null,
  },
  rules: {
    processCode: [
      { 
        required: true, 
        message: "工序编码不能为空", 
        trigger: "blur",
        // 自定义验证规则：自动生成时允许为空（由系统生成）
        validator: (rule, value, callback) => {
          if (data.form.autoGenerate) {
            callback();  // 自动生成模式，跳过验证
          } else if (!value) {
            callback(new Error("工序编码不能为空"));
          } else {
            callback();
          }
        }
      }
    ],
    processName: [
      { required: true, message: "工序名称不能为空", trigger: "blur" }
    ],
    enableFlag: [
      { required: true, message: "请选择是否启用", trigger: "change" }
    ]
  }
});

// 解构响应式数据
const { queryParams, form, rules } = toRefs(data);
// 1. 处理列表数据：为每条记录添加“是否显示完整内容”的属性
const handleProcessList = (list) => {
  return list.map(item => ({
    ...item,
    showFullAttention: false // 初始：不显示完整内容（显示省略）
  }));
};
/**
 * 查询工序列表（修改：处理列表数据，添加显示状态属性）
 */
function getList() {
  loading.value = true;
  listProcess(queryParams.value).then(response => {
    // 处理数据，添加显示状态属性
    processList.value = handleProcessList(response.rows);
    total.value = response.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}
/**
 * 2. 点击切换工序说明的显示状态
 */
function toggleAttention(row) {
  row.showFullAttention = !row.showFullAttention;
}

/**
 * 3. 辅助判断：文本是否可能超出3行（简化版，基于字符长度估算）
 * 注：精确判断需通过DOM计算，此处用字符长度估算（1行≈20个中文字符，3行≈60个）
 */
function isTextOverflow(text) {
  return text.length > 60; // 可根据实际字体大小调整阈值
}
/**
 * 取消操作
 */
function cancel() {
  open.value = false;
  reset();
}

/**
 * 重置表单
 */
function reset() {
  form.value = {
    autoGenerate: true,
    processId: null,
    processCode: "",
    processName: "",
    attention: "",
    enableFlag: "Y",
    remark: "",
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  // 重置表单验证
  if (proxy.$refs.processRef) {
    proxy.$refs.processRef.resetFields();
  }
  // 自动生成模式下生成编码
  if (form.value.autoGenerate) {
    generateProcessCode();
  }
}

/**
 * 搜索按钮点击事件
 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/**
 * 重置搜索条件
 */
function resetQuery() {
  if (proxy.$refs.queryRef) {
    proxy.$refs.queryRef.resetFields();
  }
  handleQuery();
}

/**
 * 选择项变化事件
 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.processId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/**
 * 新增按钮点击事件
 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加工序设置";
  // 自动生成编码
  if (form.value.autoGenerate) {
    generateProcessCode();
  }
}

/**
 * 修改按钮点击事件
 */
function handleUpdate(row) {
  reset();
  const processId = row ? row.processId : ids.value[0];
  getProcess(processId).then(response => {
    form.value = {
      ...response.data,
      // 编辑时保持自动生成状态（默认false）
      autoGenerate: response.data.autoGenerate ?? false
    };
    open.value = true;
    title.value = "修改工序设置";
  }).catch(() => {
    proxy.$modal.msgError("获取工序信息失败");
  });
}

/**
 * 自动生成开关变化事件
 */
function handleAutoGenerate() {
  if (form.value.autoGenerate) {
    generateProcessCode();
  } else {
    form.value.processCode = "";  // 关闭时清空编码
  }
}

/**
 * 生成工序编码
 * 这里提供两种方案：前端生成（简单场景）和后端生成（保证唯一性）
 */
function generateProcessCode() {
  // 方案1：前端生成（时间戳+随机数）
  const prefix = "PROC";
  const date = new Date();
  const year = date.getFullYear().toString().slice(-2);
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const timestamp = date.getTime().toString().slice(-6);
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  form.value.processCode = `${prefix}-${year}${month}${day}-${timestamp}-${random}`;

  // 方案2：后端生成（推荐，保证唯一性）
  // generateProcessCode().then(response => {
  //   form.value.processCode = response.data;
  // }).catch(() => {
  //   proxy.$modal.msgError("编码生成失败，请重试");
  //   form.value.autoGenerate = false;  // 生成失败时关闭自动生成
  // });
}

/**
 * 提交表单
 */
function submitForm() {
  proxy.$refs.processRef.validate(valid => {
    if (valid) {
      if (form.value.processId) {
        // 修改操作
        updateProcess(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(() => {
          proxy.$modal.msgError("修改失败");
        });
      } else {
        // 新增操作
        addProcess(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(() => {
          proxy.$modal.msgError("新增失败");
        });
      }
    }
  });
}

/**
 * 删除按钮点击事件
 */
function handleDelete(row) {
  const processIds = row ? [row.processId] : ids.value;
  proxy.$modal.confirm(`是否确认删除选中的${processIds.length}条工序数据？`).then(() => {
    return delProcess(processIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
    // 取消删除不做处理
  });
}

/**
 * 导出按钮点击事件
 */
function handleExport() {
  proxy.download('process/process/export', {
    ...queryParams.value
  }, `工序数据_${new Date().getTime()}.xlsx`);
}

// 页面初始化时加载数据
getList();
</script>

<style scoped>
/* 表格操作列宽度调整 */
::v-deep .fixed-width {
  width: 180px !important;
}

/* 搜索区域和按钮区域间距 */
.mb8 {
  margin-bottom: 8px;
}

/* 对话框按钮区域样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>
